package com.zbl.zblproject.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.core.entity.AdminUser;
import com.zbl.zblproject.core.entity.RechargeLog;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.mapper.RechargeLogMapper;
import com.zbl.zblproject.core.mapper.UserAddressMapper;
import com.zbl.zblproject.core.service.UserService;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.core.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/11/13
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private RechargeLogMapper rechargeLogMapper;


    @Override
    public List<AdminUser> getLeader() {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("group_leader", 1);
        return adminUserMapper.selectList(wrapper);
    }

    @Override
    public List<AdminUser> searchUser(String name) {
        QueryWrapper<AdminUser> userWrapper = new QueryWrapper<>();
        userWrapper.select("user_id", "user_name", "logistics", "balance");
        if(!StringUtil.isNullOrEmpty(name)){
            userWrapper.like("user_name", name);
        }
        userWrapper.gt("user_id", 3).orderByDesc("user_name");
        List<AdminUser> users = adminUserMapper.selectList(userWrapper);
        users.forEach((x)->{
            x.setAddressList(userAddressMapper.selectAddressesByUserId(x.getUserId()));
        });
        return users;
    }


    @Override
    public RechargeLog recharge(int userId, int operatorId, double price, String remarks, String imgPath) {
        if(price == 0){
            throw new RuntimeException("充值金额不能为0!");
        }
        BigDecimal money = BigDecimal.valueOf(price);
        AdminUser user = adminUserMapper.selectById(userId);
        Preconditions.checkNotNull(user, "未查询到用户!");
        RechargeLog log = new RechargeLog();
        log.setBeforeMoney(user.getBalance());
        log.setMoney(money);
        log.setTime(LocalDateTime.now());
        log.setUserId(userId);
        log.setOperatorName(adminUserMapper.selectNameById(operatorId));
        log.setMode(0);
        log.setRemarks(remarks);
        log.setImgPath(imgPath);
        user.setBalance(user.getBalance().add(money));
        rechargeLogMapper.insert(log);
        if(adminUserMapper.updateById(user) == 1){
            return log;
        }
        return null;
    }

    @Override
    public IPage<RechargeLog> logPage(int userId, int current, int size) {
        QueryWrapper<RechargeLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("mode", 0);
        IPage<RechargeLog> page = new Page<>(current, size);
        page  = rechargeLogMapper.selectPage(page, wrapper);
        page.getRecords().forEach(x->{
            x.setAdminUser(adminUserMapper.selectById(x.getUserId()));
        });
        return page;
    }

    @Override
    public IPage<RechargeLog> logPage(int current, int size, String start, String end) {
        QueryWrapper<RechargeLog> wrapper = new QueryWrapper<>();
        wrapper.eq("mode", 0);
        if (!StringUtil.isNullOrEmpty(start)) {
            wrapper.ge("time", TimeUtil.parseTime(start));
        }
        if (!StringUtil.isNullOrEmpty(end)) {
            wrapper.le("time", TimeUtil.parseTime(end));
        }
        IPage<RechargeLog> page = new Page<>(current, size);
        page = rechargeLogMapper.selectPage(page, wrapper);
        page.getRecords().forEach(x->{
            x.setAdminUser(adminUserMapper.selectById(x.getUserId()));
        });
        return page;
    }

    @Override
    public List<AdminUser> list() {
        List<AdminUser> list = adminUserMapper.selectList(null);
        list.forEach((x)->{

            x.setLeaderName(Optional.ofNullable(adminUserMapper.selectNameById(x.getGroupId())).orElse("无"));
            x.setCashierName(Optional.ofNullable(adminUserMapper.selectNameById(x.getCashierTeller())).orElse("无"));
        });
        return list;
    }

    @Override
    public List<AdminUser> snList(Integer userId) {
        List<AdminUser> list;
        if(userId == -1){
            list = adminUserMapper.selectList(null);
        }else{
            QueryWrapper<AdminUser>  wrapper = new QueryWrapper<>();
            wrapper.eq("group_id", userId);
            list = adminUserMapper.selectList(wrapper);
        }
        list.forEach((x)->{
            x.setLeaderName(Optional.ofNullable(adminUserMapper.selectNameById(x.getGroupId())).orElse("无"));
            x.setCashierName(Optional.ofNullable(adminUserMapper.selectNameById(x.getCashierTeller())).orElse("无"));
        });
        return list;
    }

    @Override
    public List<AdminUser> cashier() {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("cashier_leader", 1);
        return adminUserMapper.selectList(wrapper);
    }

    @Override
    public boolean updateUser(AdminUser user) {
        return adminUserMapper.updateById(user) == 1;
    }

    @Override
    public IPage<AdminUser> page(Integer current, Integer size, String search) {

        IPage<AdminUser> userPage = new Page<>(current, size);
        if(StringUtil.isNullOrEmpty(search)){

            QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
            wrapper.eq("is_show", 1);
            userPage = adminUserMapper.selectPage(userPage, wrapper);
        }else{
            QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", search).eq("is_show", 1);
            userPage = adminUserMapper.selectPage(userPage, wrapper);
        }
        return userPage;
    }
}
